package com.example.demo.service;

import com.example.demo.entity.Customer;
import com.example.demo.entity.OrderBase;
import com.example.demo.entity.OrderImg;
import com.example.demo.entity.OrderQuery;
import com.example.demo.repository.CustomerRepository;
import com.example.demo.repository.OrderImgRepository;
import com.example.demo.repository.OrderRepository;
import com.example.demo.repository.StatusRepository;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class OrderService {


    @Autowired
    OrderRepository orderRepository;
    @Autowired
    CustomerRepository customerRepository;
    @Autowired
    StatusRepository statusRepository;
    @Autowired
    OrderImgRepository orderImgRepository;

    public OrderBase getOrder(Integer id) {
        OrderBase order = orderRepository.findOne(id);
        return order;
    }


    public OrderBase insertOrder(Map order, HttpServletRequest request) {
        OrderBase orderBase = checkOrder(order,request);
        OrderBase save = orderRepository.save(orderBase);
        if(!StringUtils.isEmpty(order.get("imgUrl").toString())){
            String[] str = order.get("imgUrl").toString().split(",");
            orderImgRepository.deleteByOrderId(save);
            for(int i = 0;i<str.length;i++){
                System.out.println(i);
                OrderImg orderImg = new OrderImg();
                orderImg.setOrderBase(save);
                orderImg.setImgUrl(str[i]);
                orderImgRepository.save(orderImg);
            }
        }
        return save;
    }

    public OrderBase checkOrder(Map order, HttpServletRequest request){
        OrderBase baseOrder = new OrderBase();
        if( !StringUtils.isEmpty(order.get("id").toString()) ){
            baseOrder = orderRepository.findOne(Integer.valueOf(order.get("id").toString()));
        }
        else{
            baseOrder.setUpdateTime(new Date());
            HttpSession session = request.getSession();
            String userId = session.getAttribute("user").toString().toString();
            baseOrder.setUpdater(userId);
        }
        if( !StringUtils.isEmpty(order.get("proName").toString()) ){
            baseOrder.setProName( order.get("proName").toString() );
        }
        if( !StringUtils.isEmpty(order.get("customerId").toString()) ){
            baseOrder.setCustomer(customerRepository.findOne(Integer.valueOf(order.get("customerId").toString())));
        }
        if( !StringUtils.isEmpty(order.get("proQuantity").toString()) ){
            baseOrder.setProQuantity(  Integer.valueOf(order.get("proQuantity").toString()) );
        }
        if( !StringUtils.isEmpty(order.get("orderPay").toString()) ){
            baseOrder.setOrderPay(statusRepository.findOne(Integer.valueOf(order.get("orderPay").toString())) );
        }
        if( !StringUtils.isEmpty(order.get("payTime").toString()) ){
            baseOrder.setPayTime( new Date(Long.valueOf(order.get("payTime").toString())) );
        }
        if( !StringUtils.isEmpty(order.get("proPrice").toString()) ){
            baseOrder.setProPrice(  Integer.valueOf(order.get("proPrice").toString()) );
        }
        if( !StringUtils.isEmpty(order.get("proTotal").toString()) ){
            baseOrder.setProTotal(  Integer.valueOf(order.get("proTotal").toString()) );
        }
        if( !StringUtils.isEmpty(order.get("orderStatus").toString()) ){
            baseOrder.setOrderStatus(  statusRepository.findOne(Integer.valueOf(order.get("orderStatus").toString())) );
        }
        if( !StringUtils.isEmpty(order.get("payBank").toString()) ){
            baseOrder.setPayBank(  order.get("payBank").toString() );
            baseOrder.setBankTime(new Date());
        }
        if( !StringUtils.isEmpty(order.get("orderWord").toString()) ){
            baseOrder.setOrderWord(  order.get("orderWord").toString() );
        }
        return  baseOrder;
    }

    public List<OrderBase> orderAll() {
        List<OrderBase> order = orderRepository.findAll();
        return order;
    }

    public List<OrderBase> orderCount() {
        List<OrderBase> order = orderRepository.findAll();
        return order;
    }

    public Long countAllByUpdater(String userId) {
        Long orderCount = orderRepository.countAllByUpdater(userId);
        return orderCount;
    }


    public Page<OrderBase> findBookCriteria(Integer page, Integer size, final Map orderQuery,String userId) {
        Pageable pageable = new PageRequest(page, size, Sort.Direction.DESC, "id");
        Page<OrderBase> orderPage = orderRepository.findAll(new Specification<OrderBase>() {
            public Predicate toPredicate(Root<OrderBase> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> lstPredicates = new ArrayList<Predicate>();
                if( !StringUtils.isEmpty(orderQuery.get("id")) ){
                    lstPredicates.add(criteriaBuilder.like(root.get("id").as(String.class), "%"+orderQuery.get("id")+"%"));
                }
                lstPredicates.add(criteriaBuilder.equal(root.get("updater").as(String.class), userId));
                Predicate[] arrayPredicates = new Predicate[lstPredicates.size()];
                return criteriaBuilder.and(lstPredicates.toArray(arrayPredicates));
            }
        }, pageable);
        return orderPage;
    }

    public Boolean orderDelete(Integer id){
        orderImgRepository.deleteByOrderId(orderRepository.findOne(id));
        orderRepository.delete(id);
        return true;
    }

    public void orderPay(Integer id,String payBank){
        OrderBase order = orderRepository.findOne(id);
        order.setPayBank(payBank);
        order.setBankTime(new Date());
        order.setOrderPay(statusRepository.findOne(7));
        orderRepository.save(order);
    }

    public void orderSend(Integer id){
        OrderBase order = orderRepository.findOne(id);
        order.setOrderStatus(statusRepository.findOne(4));
        orderRepository.save(order);
    }
    public void orderDone(Integer id){
        OrderBase order = orderRepository.findOne(id);
        order.setOrderStatus(statusRepository.findOne(5));
        orderRepository.save(order);
    }

}


